package com.treasure.mall.biz.remote.track;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.treasure.mall.biz.remote.track.dto.ReceiveInfo;
import com.treasure.mall.biz.remote.track.dto.kd100.KD100CallBackResp;
import com.treasure.mall.biz.remote.track.dto.kd100.KD100QueryResp;
import com.treasure.mall.biz.remote.track.dto.kd100.KD100SubRequest;
import com.treasure.mall.biz.remote.track.dto.kd100.KD100SubResp;
import com.treasure.mall.biz.remote.track.enums.LogisticsStatus;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.base.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/9
 */
@Service
@ConditionalOnProperty(
        value = {"zbq.remote.track.kuaidi100.enable"},
        havingValue = "true",
        matchIfMissing = true
)
public class KD100LogisticsProvider implements LogisticsProvider {
    @Value("${zbq.remote.track.kuaidi100.queryUrl}")
    private String queryUrl;
    @Value("${zbq.remote.track.kuaidi100.subUrl}")
    private String subUrl;
    @Value("${zbq.remote.track.kuaidi100.customer}")
    private String customer;
    @Value("${zbq.remote.track.kuaidi100.key}")
    private String key;
    @Value("${zbq.remote.track.kuaidi100.subCallbackUrl}")
    private String callbackUrl;

    @Override
    public ApiResult query(String companyCode, String trackingNo) {
        try {
            String param = "{\"com\":\"" + companyCode + "\",\"num\":\"" + trackingNo + "\"}";
            //签名
            String signStr = param + key + customer;
            String sign = DigestUtils.md5DigestAsHex(signStr.getBytes()).toUpperCase();
            Map<String, Object> requestData = new HashMap<>();

            requestData.put("customer", customer);
            requestData.put("sign", sign);
            requestData.put("param", param);

            String result = HttpUtil.post(queryUrl, requestData);
            KD100QueryResp resp = JSON.parseObject(result, KD100QueryResp.class);
            if ("ok".equals(resp.getMessage())) {
                return ApiResult.resultWith(ResultCodeEnum.SUCCESS, resp.toTrackInfo());
            }
            return ApiResult.errorWith(ResultCodeEnum.THIRD_ERROR);
        } catch (Exception ex) {
            return ApiResult.errorWith(ResultCodeEnum.THIRD_ERROR, ex.getMessage());
        }
    }

    @Override
    public ApiResult subscribe(String comCode, String expressNo) {
        try {
            KD100SubRequest subRequest = new KD100SubRequest();
            subRequest.setCompany(comCode);
            subRequest.setNumber(expressNo);
            subRequest.setKey(key);
            Map<String, String> parameters = new HashMap<>();
            parameters.put("callbackurl", callbackUrl);
            subRequest.setParameters(parameters);

            Map<String, Object> requestData = new HashMap<>();
            requestData.put("schema", "json");
            requestData.put("param", JSON.toJSONString(subRequest));

            KD100SubResp resp = JSON.parseObject(HttpUtil.post(subUrl, requestData), KD100SubResp.class);

            if (resp.isResult() && "200".equals(resp.getReturnCode())) {
                return ApiResult.resultWith(ResultCodeEnum.SUCCESS);
            }
            return ApiResult.errorWith(ResultCodeEnum.THIRD_ERROR, resp.getMessage());
        } catch (Exception ex) {
            return ApiResult.errorWith(ResultCodeEnum.THIRD_ERROR, ex.getMessage());
        }
    }

    @Override
    public ReceiveInfo subCallback(HttpServletRequest request) {
        String param = request.getParameter("param");

        JSONObject object = JSON.parseObject(param);
        JSONObject resultJson = object.getJSONObject("lastResult");
        String status = resultJson.getString("state");

        ReceiveInfo receiveInfo = new ReceiveInfo();
        receiveInfo.setExpressComCode(resultJson.getString("com"));
        receiveInfo.setExpressNo(resultJson.getString("nu"));
        if ("3".equals(status)) {
            //签收成功
            receiveInfo.setLogisticsStatus(LogisticsStatus.RECEIVED);
        } else {
            receiveInfo.setLogisticsStatus(LogisticsStatus.OTHER);
        }

        return receiveInfo;
    }

    @Override
    public void callbackResp(HttpServletResponse response) throws IOException {
        KD100CallBackResp resp = new KD100CallBackResp();
        resp.setResult(true);
        resp.setReturnCode("200");
        resp.setMessage("成功");

        response.getWriter().print(JSON.toJSONString(resp));
    }
}
